import React, { useMemo, useState } from 'react';
import { Spin, message } from 'antd';
import { isOriginSource } from '../utils';
import styles from './index.less';

/**
 * 图片预览
 * @param {boolean} visible - 是否显示
 * @param {string} origin - 以http或https开头的远端资源
 * @param onError
 * @param style
 * @param className
 * @param encode
 * @callback onError - 错误回调
 */
const ImagePreview = ({ visible, origin, onError, style, className, encode }) => {
    const [loading, setLoading] = useState(false);
    const imageSrc = useMemo(() => {
        if (isOriginSource(origin)) {
            setLoading(true);
            return encode ? encodeURIComponent(origin) : origin;
        }
        return null;
    }, [encode, origin]);

    const endLoading = () => {
        setLoading(false);
    };

    const handleError = () => {
        const errorMsg = '图片加载失败!';
        if (onError) {
            onError(errorMsg);
        } else {
            message.error(errorMsg);
        }
        endLoading();
    };

    return (
        imageSrc &&
        visible && (
            <>
                <Spin spinning={loading}>
                    <div className={styles.imageContainer}>
                        <img
                            src={imageSrc}
                            onLoad={endLoading}
                            alt=""
                            onError={handleError}
                            style={{ width: '100%', ...style }}
                            className={className}
                        />
                    </div>
                </Spin>
            </>
        )
    );
};

export default ImagePreview;
